<?php
/* 
 * name        : Internal » Sitemap
 * description : Generate and display a sitemap.  Useful for SEO.
 * context     : page
 * instructions: There are two configuration options; include_regex and exclude_regex.  Both are optional.
 * 
 */

$default_config = array(
	'include_regex' => '/.*/',
	'exclude_regex' => '/^[^\/]/'
);

$config = array_merge($default_config, parse_config($config));

echo "<ul class=\"sitemap\">";
sitemap(0, '/', 0, $config);
echo "</ul>";

function sitemap($parent_id, $curpath, $level, $config) {
	global $site, $db;
	$pages = $db->fetchAll("SELECT p.*, r.title, r.path FROM site_pages p LEFT JOIN site_pages_revisions r ON p.revision_id=r.id WHERE site_id=? AND parent_id=? AND active=1 ORDER BY sort", array($site['id'], $parent_id));
	foreach($pages as $page) {
		$this_path = preg_replace("/\/\//", '/', $curpath . $page['path'] . '/');
		if (!preg_match($config['exclude_regex'], $this_path) and preg_match($config['include_regex'], $this_path)) {
			echo '<li><a href="', $this_path, '">', htmlentities($page['title'], ENT_QUOTES, 'utf-8'), '</a><ul>';
			sitemap($page['id'], $this_path, $level+1, $config);
			echo '</ul></li>';
		}
	}
}